<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm"></BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { computed, ref, unref, defineEmits } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/form';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from '../data/data';
import { add, get, update } from '../data/api';

const isUpdate = ref(true);
const emit = defineEmits(['register', 'success']);
const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
  labelWidth: 150,
  labelCol: { span: 6 },
  schemas: formSchema,
  showActionButtonGroup: false,
  showAdvancedButton: false,
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    const vipcardId = data.record.vipcardId;
    data.record = await get({ vipcardId: vipcardId, handlerName: 'busVipCardGetHandler' });
    setFieldsValue({
      ...data.record,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增卡种' : '编辑卡种'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await update(values);
    } else {
      await add(values);
    }
    console.log(values);
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
